package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.RedisData;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisClient;
import com.hmdp.utils.RedisConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //Redis工具类
    @Autowired
    private RedisClient redisClient;

    @Override
    public Result queryById(Long id) {


        //Shop shop = queryWithMutex(id);
        //Shop shop = queryWithLogicalExpire(id);
        //Shop shop = redisClient.queryWithPassThrough(CACHE_SHOP_KEY + id, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);
        Shop shop = redisClient.queryWithLogicalExpire(CACHE_SHOP_KEY + id, LOCK_SHOP_KEY + id, id,
                Shop.class, this::getById, LOCK_SHOP_TTL, TimeUnit.SECONDS);
        if (shop == null){
            return Result.fail("商铺不存在");
        }
        return Result.ok(shop);
    }

    public static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
    //逻辑过期方式解决缓存击穿问题
    public Shop queryWithLogicalExpire(Long id){
        String key = CACHE_SHOP_KEY + id;
        //从redis查询商铺缓存
        String cacheShop = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isBlank(cacheShop)) {
            //如果不存在，直接空
            return null;
        }
        //判断缓存是否过期
        RedisData redisData = JSONUtil.toBean(cacheShop, RedisData.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        JSONObject shopData = (JSONObject) redisData.getData();
        Shop shop = JSONUtil.toBean(shopData, Shop.class);
        if (expireTime.isAfter(LocalDateTime.now())){
            //未过期,直接返回商铺信息
            return shop;
        }
        //已过期,尝试获取互斥锁
        //判断互斥锁是否获取成功
        String keyLock = LOCK_SHOP_KEY + id;
            Boolean isLock = tryLock(keyLock);
            if (isLock){
                //获取成功,进行DoubleCheck判断redis缓存是否过期
                String cacheShopDouble = stringRedisTemplate.opsForValue().get(key);
                RedisData redisDataDouble = JSONUtil.toBean(cacheShopDouble, RedisData.class);
                LocalDateTime expireTimeDouble = redisDataDouble.getExpireTime();
                if (expireTimeDouble.isAfter(LocalDateTime.now())){
                    //未过期,直接返回商铺信息
                    JSONObject shopDataDouble = (JSONObject) redisDataDouble.getData();
                    unLock(keyLock);
                    return JSONUtil.toBean(shopDataDouble, Shop.class);
                }
                // 已过期，开启独立线程,实现缓存重建
                CACHE_REBUILD_EXECUTOR.submit(() ->{
                    try {
                        //缓存重建
                        saveShop2ById(id,20L);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    } finally {
                        //释放锁
                        unLock(keyLock);
                    }
                });
            }
            //获取失败直接返回商铺信息
        return shop;
    }


    //互斥锁解决缓存击穿问题
    public Shop queryWithMutex(Long id){
        String key = CACHE_SHOP_KEY + id;
        //从redis查询商铺缓存
        String cacheShop = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(cacheShop)) {
            //如果存在，直接返回
            return JSONUtil.toBean(cacheShop, Shop.class);
        }
        //判断cacheShop是否为空串
        // if(cacheShop.equals(""))
        if (cacheShop != null){
            return null;
        }
        //获取互斥锁，判断互斥锁是否获取成功
        String keyLock = LOCK_SHOP_KEY + id;
        Shop shop = null;
        try {
            Boolean isLock = tryLock(keyLock);
            if (!isLock){
                //如果获取失败，休眠一段时间，重启查询redis缓存
                Thread.sleep(50);
                return queryWithMutex(id);
            }
            //如果获取成功，进行DoubleCheck判断redis缓存是否存在
            String cacheShopDouble = stringRedisTemplate.opsForValue().get(key);
            if (StrUtil.isNotBlank(cacheShopDouble)) {
                //如果存在，直接返回
                return JSONUtil.toBean(cacheShopDouble, Shop.class);
            }
            if (cacheShopDouble != null){
                return null;
            }

            //如果不存在，查询数据库
            shop = getById(id);
            if (shop == null){
                //如果数据库中不存在,返回空给redis缓存
                stringRedisTemplate.opsForValue().set(key,"", CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            //如果存在,先将商铺数据写入redis中，再返回商铺信息
            String jsonShop = JSONUtil.toJsonStr(shop);
            stringRedisTemplate.opsForValue().set(key,jsonShop, CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            //释放锁
            unLock(keyLock);
        }
        return  shop;
    }
    //redis缓存重建
    public void saveShop2ById(Long id, Long expireTime) throws InterruptedException {
        Shop shop = getById(id);
        //模拟重建延迟
        Thread.sleep(200);

        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireTime));
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id,JSONUtil.toJsonStr(redisData));
    }

    private Boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", LOCK_SHOP_TTL, TimeUnit.SECONDS);
        return flag != null && flag;
    }

    private void unLock(String key){
        stringRedisTemplate.delete(key);
    }

    @Override
    @Transactional
    public Result updateShopById(Shop shop) {
        //判断shopId是否为空
        if (shop.getId() == null) {
            return Result.fail("店铺id不能为空");
        }
        //更新数据库
        updateById(shop);
        //删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + shop.getId());
        return Result.ok();

    }
}
